package com.loopj.ohos.http.sample;

import com.loopj.ohos.http.AsyncHttpClient;
import com.loopj.ohos.http.AsyncHttpResponseHandler;
import com.loopj.ohos.http.RequestHandle;
import com.loopj.ohos.http.ResponseHandlerInterface;

import com.loopj.ohos.http.ext.LocalHiLog;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpEntity;

/**
 * CancelRequestByTagSample
 */
public class CancelRequestByTagSample extends ThreadingTimeoutSample {

    private static final String LOG_TAG = "CancelRequestByTagSample";
    private static final Integer REQUEST_TAG = 132435;

    @Override
    public int getSampleTitle() {
        return ResourceTable.String_title_cancel_tag;
    }

    @Override
    public void onCancelButtonPressed() {
        LocalHiLog.info(LOG_TAG, "Canceling requests by TAG: " + REQUEST_TAG);
        getAsyncHttpClient().cancelRequestsByTAG(REQUEST_TAG, false);
    }

    @Override
    public ResponseHandlerInterface getResponseHandler() {
        return new AsyncHttpResponseHandler() {

            private final int id = counter++;

            @Override
            public void onStart() {
                setStatus(id, "TAG:" + getTag() + ", START");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                setStatus(id, "SUCCESS");
            }

            @Override
            public void onFinish() {
                setStatus(id, "FINISH");
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                setStatus(id, "FAILURE");
            }

            @Override
            public void onCancel() {
                setStatus(id, "CANCEL");
            }
        };
    }

    @Override
    public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) {
        return client.get(this, URL, headers, null, responseHandler).setTag(REQUEST_TAG);
    }
}
